<template>
  <div class="tools-example">
    <h1>常用工具使用示例</h1>
    
    <!-- 状态管理示例 -->
    <section class="section">
      <h2>🗃️ 状态管理 (useStore)</h2>
      <div class="demo-card">
        <p>当前主题: {{ store.getState().app.theme }}</p>
        <p>用户名: {{ store.getState().user.userInfo?.name || '未登录' }}</p>
        <div class="buttons">
          <button @click="toggleTheme">切换主题</button>
          <button @click="setUser">设置用户</button>
          <button @click="clearStore">清空状态</button>
        </div>
      </div>
    </section>

    <!-- 缓存管理示例 -->
    <section class="section">
      <h2>💾 缓存管理 (useCache)</h2>
      <div class="demo-card">
        <p>缓存项数量: {{ cacheSize }}</p>
        <div class="buttons">
          <button @click="setCacheData">设置缓存</button>
          <button @click="getCacheData">获取缓存</button>
          <button @click="clearCache">清空缓存</button>
        </div>
        <p v-if="cachedData">缓存数据: {{ JSON.stringify(cachedData) }}</p>
      </div>
    </section>

    <!-- 本地存储示例 -->
    <section class="section">
      <h2>💿 本地存储 (useStorage)</h2>
      <div class="demo-card">
        <input 
          v-model="storageValue" 
          placeholder="输入要存储的值"
          class="input"
        />
        <p>存储的值: {{ storageValue }}</p>
        <div class="buttons">
          <button @click="clearStorage">清空存储</button>
        </div>
      </div>
    </section>

    <!-- 表单验证示例 -->
    <section class="section">
      <h2>✅ 表单验证 (useValidation)</h2>
      <div class="demo-card">
        <form @submit="handleSubmit">
          <div class="form-group">
            <label>姓名 *</label>
            <input 
              v-model="formData.name" 
              placeholder="请输入姓名"
              class="input"
              :class="{ error: nameValidation.validation.value.isTouched && !nameValidation.validation.value.isValid }"
            />
            <span v-if="nameValidation.validation.value.isTouched && !nameValidation.validation.value.isValid" class="error-text">
              {{ nameValidation.validation.value.message }}
            </span>
          </div>
          
          <div class="form-group">
            <label>邮箱 *</label>
            <input 
              v-model="formData.email" 
              placeholder="请输入邮箱"
              class="input"
              :class="{ error: emailValidation.validation.value.isTouched && !emailValidation.validation.value.isValid }"
            />
            <span v-if="emailValidation.validation.value.isTouched && !emailValidation.validation.value.isValid" class="error-text">
              {{ emailValidation.validation.value.message }}
            </span>
          </div>
          
          <div class="buttons">
            <button type="submit" :disabled="!isFormValid">提交</button>
            <button type="button" @click="resetForm">重置</button>
          </div>
        </form>
      </div>
    </section>

    <!-- 防抖节流示例 -->
    <section class="section">
      <h2>⏱️ 防抖节流 (useDebounce)</h2>
      <div class="demo-card">
        <div class="form-group">
          <label>防抖输入 (300ms)</label>
          <input 
            v-model="debounceInput.inputValue" 
            placeholder="输入内容..."
            class="input"
          />
          <p>防抖后的值: {{ debounceInput.debouncedValue }}</p>
          <p v-if="debounceInput.isPending" class="pending">⏳ 等待中...</p>
        </div>
        
        <div class="form-group">
          <label>节流按钮 (1000ms)</label>
          <button @click="throttledClick" class="throttle-btn">
            点击我 ({{ clickCount }})
          </button>
        </div>
      </div>
    </section>

    <!-- 通用工具示例 -->
    <section class="section">
      <h2>🔧 通用工具 (utils/common)</h2>
      <div class="demo-card">
        <div class="tool-demo">
          <h4>字符串工具</h4>
          <p>原文: "hello world"</p>
          <p>首字母大写: {{ utils.capitalize('hello world') }}</p>
          <p>截断: {{ utils.truncate('这是一个很长的文本内容', 10) }}</p>
        </div>
        
        <div class="tool-demo">
          <h4>数字工具</h4>
          <p>格式化数字: {{ utils.formatNumber(1234567.89) }}</p>
          <p>限制范围: {{ utils.clamp(150, 0, 100) }}</p>
        </div>
        
        <div class="tool-demo">
          <h4>日期工具</h4>
          <p>格式化日期: {{ utils.formatDate(new Date()) }}</p>
          <p>相对时间: {{ utils.formatRelativeTime(new Date(Date.now() - 3600000)) }}</p>
        </div>
        
        <div class="tool-demo">
          <h4>数组工具</h4>
          <p>去重: {{ utils.unique([1, 2, 2, 3, 3, 4]) }}</p>
          <p>分组: {{ JSON.stringify(utils.groupBy(sampleData, 'type')) }}</p>
        </div>
        
        <div class="buttons">
          <button @click="copyText">复制文本到剪贴板</button>
          <button @click="showDeviceInfo">显示设备信息</button>
        </div>
      </div>
    </section>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive } from 'vue'
import { useStore } from '../composables/useStore'
import { useCache } from '../composables/useCache'
import { useLocalStorage } from '../composables/useStorage'
import { useFieldValidation, validationRules } from '../composables/useValidation'
import { 
  useInputDebounce, 
  useThrottleFn
} from '../composables/useDebounce'
import { utils } from '../utils/common'

// 状态管理
const store = useStore()
const { setTheme } = store.useAppState()
const { setUserInfo, clearUserState } = store.useUserState()

const toggleTheme = () => {
  const currentTheme = store.getState().app.theme
  setTheme(currentTheme === 'light' ? 'dark' : 'light')
}

const setUser = () => {
  setUserInfo({
    id: '1',
    name: '张三',
    email: 'zhangsan@example.com'
  })
}

const clearStore = () => {
  clearUserState()
}

// 缓存管理
const cache = useCache()
const cacheSize = ref(0)
const cachedData = ref<any>(null)

const setCacheData = () => {
  cache.set('demo-key', { message: 'Hello Cache!', timestamp: Date.now() }, { expiry: 60000 })
  cacheSize.value++
}

const getCacheData = () => {
  cachedData.value = cache.get('demo-key')
}

const clearCache = () => {
  cache.clear()
  cachedData.value = null
  cacheSize.value = 0
}

// 本地存储
const { value: storageValue } = useLocalStorage('demo-storage', '默认值')

const clearStorage = () => {
  storageValue.value = ''
}

// 表单验证
const formData = reactive({
  name: '',
  email: ''
})

const nameValidation = useFieldValidation(
  () => formData.name,
  [validationRules.required()]
)

const emailValidation = useFieldValidation(
  () => formData.email,
  [validationRules.required(), validationRules.email()]
)

const isFormValid = computed(() => {
  return nameValidation.validation.value.isValid && 
         emailValidation.validation.value.isValid
})

const handleSubmit = (event: Event) => {
  event.preventDefault()
  nameValidation.touch()
  emailValidation.touch()
  
  if (isFormValid.value) {
    console.log('表单提交:', formData)
    alert('表单验证通过！')
  }
}

const resetForm = () => {
  formData.name = ''
  formData.email = ''
  nameValidation.reset()
  emailValidation.reset()
}

// 防抖输入
const debounceInput = useInputDebounce('', 300)

// 节流点击
const clickCount = ref(0)
const throttledClick = useThrottleFn(() => {
  clickCount.value++
}, 1000)

// 通用工具示例数据
const sampleData = [
  { id: 1, name: '苹果', type: '水果' },
  { id: 2, name: '香蕉', type: '水果' },
  { id: 3, name: '胡萝卜', type: '蔬菜' },
  { id: 4, name: '白菜', type: '蔬菜' }
]

const copyText = async () => {
  try {
    await utils.copyToClipboard('这是复制的文本内容')
    alert('文本已复制到剪贴板！')
  } catch (error) {
    alert('复制失败')
  }
}

const showDeviceInfo = () => {
  const deviceInfo = utils.getDeviceInfo()
  alert(`设备信息:\n${JSON.stringify(deviceInfo, null, 2)}`)
}
</script>

<style scoped>
.tools-example {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

h1 {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 40px;
}

.section {
  margin-bottom: 40px;
}

h2 {
  color: #34495e;
  border-bottom: 2px solid #3498db;
  padding-bottom: 10px;
  margin-bottom: 20px;
}

.demo-card {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #495057;
}

.input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ced4da;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.15s ease-in-out;
}

.input:focus {
  outline: none;
  border-color: #80bdff;
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

.input.error {
  border-color: #dc3545;
}

.error-text {
  color: #dc3545;
  font-size: 12px;
  margin-top: 5px;
  display: block;
}

.buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

button {
  padding: 8px 16px;
  border: 1px solid #007bff;
  background-color: #007bff;
  color: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.15s ease-in-out;
}

button:hover:not(:disabled) {
  background-color: #0056b3;
  border-color: #0056b3;
}

button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.throttle-btn {
  background-color: #28a745;
  border-color: #28a745;
}

.throttle-btn:hover {
  background-color: #218838;
  border-color: #1e7e34;
}

.tool-demo {
  margin-bottom: 20px;
  padding: 15px;
  background: white;
  border-radius: 4px;
  border: 1px solid #dee2e6;
}

.tool-demo h4 {
  margin: 0 0 10px 0;
  color: #495057;
}

.tool-demo p {
  margin: 5px 0;
  font-size: 14px;
}

.pending {
  color: #ffc107;
  font-style: italic;
}

.loading {
  color: #17a2b8;
  font-style: italic;
}

.error {
  color: #dc3545;
  font-style: italic;
}

.search-results {
  list-style: none;
  padding: 0;
  margin: 10px 0 0 0;
}

.search-results li {
  padding: 8px;
  background: white;
  border: 1px solid #dee2e6;
  border-radius: 4px;
  margin-bottom: 5px;
}
</style>